﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using YLClient.Util;
using System.Threading.Tasks;

using YLPublicService.TransferModel;
using YLClient.YLServiceClient;
using YLPublicService.EnumExtension;
using YLClient.BLL;
using YLClient.Config;

namespace YLClient.UserControls
{
    /// <summary>
    /// Interaction logic for Item.xaml
    /// </summary>
    public partial class Item : UserControl
    {
        private Item()
        {
            InitializeComponent();
        }
        public Item(IWorkItem i)
            : this()
        {
            item = i;
            lblID.Content = item.WorkItemID;
            lblTime.Content = item.DBTime.ToShortDateString();
            lblDiscription.Content = item.GetDiscription();

            txtbStatus.Text = item.Status.TryGetEnumMemberValue();
            if (item.Status == WorkItemStatus.ProcessFinish ||
                item.Status == WorkItemStatus.Downloaded ||
                item.Status == WorkItemStatus.Downloading)
            {
                btnDownload.IsEnabled = true;
            }
        }
        private IWorkItem item;
        Task task;
        ServiceClient client;

        private void btnDownload_Click(object sender, RoutedEventArgs e)
        {
            client = ServiceClient.GetServiceClient();
            var isSuccess = client.UpdatedWorkItemStatus(item.CastToSerialization(), WorkItemStatus.Downloading);
            if (isSuccess == false)
            {
                MessageBox.Show("连接服务器失败，请重试。");
                return;
            }
            //从配置文件中获取保存目录
            string dir = ClientConfig.WorkItemSaveDir;

            ClientAdapter clientAdapter = new ClientAdapter(false);

            isSuccess = clientAdapter.DownloadFile(item.CastToSerialization(), dir);
            if (isSuccess == false)
            {
                MessageBox.Show("下载文件失败，请重试。");
            }
            else
            {
                MessageBox.Show("下载成功，请查看：" + Config.ClientConfig.WorkItemSaveDir);
            }
        }

        void clientAdapter_OnTransferFileError(string fileName, int index)
        {
            txtbStatus.Text = "下载失败请重试";
        }

        void clientAdapter_OnTransferFinish(bool hasErr)
        {
            //if (hasErr == false)
            //{
            //    txtbStatus.Text = "下载成功";
            //    var ret = client.UpdatedWorkItemStatus(item, WorkItemStatus.Downloaded);
            //    Console.WriteLine(ret);
            //}
        }

    }
}
